package cn.wolfcode.trip.api.interceptor;

import cn.wolfcode.trip.core.util.RequriedLogin;
import cn.wolfcode.trip.core.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LonginInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof HandlerMethod){
            // 获取当前执行的方法
            HandlerMethod method = (HandlerMethod) handler;
            // 判断是否有@RequriedLogin注解,如果有就判断是否是登录状态
            if(method.hasMethodAnnotation(RequriedLogin.class) && UserContext.getCurrentUser()==null){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码401
                return false;
            }
        }
        return true;
    }
}
